package models

import (
	"context"
	"go-chain-api/global"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/bson/primitive"
)

type ChainToChain struct {
	Id             string               `bson:"_id,omitempty" json:"id"`
	ChainConfigId0 string               `bson:"chainConfigId0" json:"chainConfigId0"`
	ChainConfigId1 string               `bson:"chainConfigId1" json:"chainConfigId1"`
	UserId         string               `bson:"userId" json:"userId"`
	Token0         string               `bson:"token0" json:"token0"`
	Token1         string               `bson:"token1" json:"token1"`
	Rate           primitive.Decimal128 `bson:"rate" json:"rate"`
}

type CreateChainData struct {
	Id             string
	UserId         string
	ChainConfigId0 string
	ChainConfigId1 string
	Token0         string
	Token1         string
	Rate           string
}

func (c *ChainToChain) ApiList(userId string) ([]bson.M, error) {
	var list []bson.M
	//cfg := configs.Get().Mongodb
	keyClient := global.DBEngine.Database(global.DbConfig.DbName).Collection("chain_to_chain")
	find, err := keyClient.Find(context.TODO(), bson.D{{"userId", userId}})
	if err != nil {
		return nil, err
	}
	err = find.All(context.TODO(), &list)
	return list, nil
}

func (c *ChainToChain) GetRate(data *CreateChainData) (ChainToChain, error) {
	var model ChainToChain
	model.UserId = data.UserId
	model.Token0 = data.Token0
	model.Token1 = data.Token1
	model.ChainConfigId0 = data.ChainConfigId0
	model.ChainConfigId1 = data.ChainConfigId1

	var result ChainToChain
	chainClient := global.DBEngine.Database(global.DbConfig.DbName).Collection("chain_to_chain")
	filter := bson.M{"chainConfigId0": model.ChainConfigId0, "chainConfigId1": model.ChainConfigId1, "userId": model.UserId, "token0": model.Token0, "token1": model.Token1}
	err := chainClient.FindOne(context.TODO(), filter).Decode(&result)
	//result, err := model.FindOne(s.db.GetDb())
	return result, err
}
